// ProfileDataScreen.kt
package com.example.nutritionmanager.profile

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.nutritionmanager.bodys.responseBodys.DailyNutritionResponse
import com.example.nutritionmanager.bodys.responseBodys.MealRecord
import com.example.nutritionmanager.viewModels.RecordState
import com.example.nutritionmanager.viewModels.RecordViewModel
import java.time.LocalDate
import java.time.format.DateTimeFormatter

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileDataScreen(
    recordViewModel: RecordViewModel = hiltViewModel()
) {
    val recordState by recordViewModel.recordState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }

    // 日期选择器状态
    var showDatePicker by remember { mutableStateOf(false) }
    var selectedDate by remember { mutableStateOf(LocalDate.now()) }

    // 在Composable首次启动时获取当天的营养记录
    LaunchedEffect(Unit) {
        recordViewModel.fetchRecordsByDate(selectedDate.format(DateTimeFormatter.ISO_DATE))
    }

    // 监听日期变化
    LaunchedEffect(selectedDate) {
        recordViewModel.fetchRecordsByDate(selectedDate.format(DateTimeFormatter.ISO_DATE))
    }

    Scaffold(
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xFFf1f1f1))
                .padding(16.dp)
                .verticalScroll(rememberScrollState())
                .padding(paddingValues)
        ) {
            // 标题和日期选择
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "饮食记录",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.Black
                )
                IconButton(onClick = { showDatePicker = true }) {
                    Icon(
                        imageVector = Icons.Default.DateRange,
                        contentDescription = "选择日期",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }

            // 显示当前选择的日期
            Text(
                text = selectedDate.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")),
                fontSize = 16.sp,
                color = Color.Gray,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            when (recordState) {
                is RecordState.Loading -> {
                    Box(
                        modifier = Modifier.fillMaxWidth(),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }
                is RecordState.Success -> {
                    val response = (recordState as RecordState.Success).response
                    // 按餐次分组显示
                    MealTypeSection("早餐", response.breakfast)
                    MealTypeSection("午餐", response.lunch)
                    MealTypeSection("晚餐", response.dinner)
                    MealTypeSection("加餐", response.snacks)
                }
                is RecordState.Error -> {
                    Text(
                        text = (recordState as RecordState.Error).error,
                        color = Color.Red,
                        modifier = Modifier.padding(16.dp)
                    )
                }
                else -> {
                    Text(
                        text = "暂无记录",
                        color = Color.Gray,
                        modifier = Modifier.padding(16.dp)
                    )
                }
            }
        }
    }

    // 日期选择器对话框
    if (showDatePicker) {
        val datePickerState = rememberDatePickerState(
            initialSelectedDateMillis = selectedDate.toEpochDay() * 24 * 60 * 60 * 1000
        )
        
        DatePickerDialog(
            onDismissRequest = { showDatePicker = false },
            confirmButton = {
                TextButton(
                    onClick = {
                        datePickerState.selectedDateMillis?.let { millis ->
                            selectedDate = LocalDate.ofEpochDay(millis / (24 * 60 * 60 * 1000))
                        }
                        showDatePicker = false
                    }
                ) {
                    Text("确定")
                }
            }
        ) {
            DatePicker(state = datePickerState)
        }
    }
}

@Composable
fun MealTypeSection(title: String, records: List<MealRecord>) {
    if (records.isEmpty()) return

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
    ) {
        Text(
            text = title,
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            color = Color.Black,
            modifier = Modifier.padding(bottom = 8.dp)
        )
        
        records.forEach { record ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                shape = RoundedCornerShape(12.dp),
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                ) {
                    record.nutrients.forEach { nutrient ->
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(
                                text = nutrient.name,
                                fontSize = 14.sp,
                                color = Color.Black
                            )
                            Text(
                                text = "${nutrient.amount}${nutrient.unit}",
                                fontSize = 14.sp,
                                color = Color.Gray
                            )
                        }
                    }
                }
            }
        }
    }
}